/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.RecordManagerOptions;
import jdbm.htree.HTree;

/**
 *
 * @author mwh
 */
public class TranslationTableJDBM implements TranslationTable {

    RecordManager recman;

    HTree translations;


    public TranslationTableJDBM(String dbName) throws IOException {


        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);
        long recid = recman.getNamedObject("translations");
        translations = HTree.load(recman, recid);

    }


    public TranslationTableJDBM(TranslationTableMem ttMem, String dbName) throws IOException {

        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);

        // Create idToName hash-translations and add TOP as element;
        translations = HTree.createInstance(recman);
        recman.setNamedObject("translations", translations.getRecid());


        for (Iterator<Integer> keyIt = ttMem.keyIterator(); keyIt.hasNext();) {

            Integer key = keyIt.next();
            Map<Integer, Double> translation = ttMem.get(key);

            translations.put(key, translation);
            recman.commit();

        }

    }


    public double get(Integer source, Integer target) {
        Map<Integer, Double> translation = get(source);
        if (translation.containsKey(target)) {
            return translation.get(target);
        } else {
            return translation.get(-1024);
        }

    }


    public Map<Integer, Double> get(Integer source) {
        try {

            return (Map<Integer, Double>) translations.get(source);
        } catch (IOException ex) {
            Logger.getLogger(TranslationTableJDBM.class.getName()).log(Level.SEVERE, null, ex);
        }

        return new HashMap<Integer, Double>();

    }


    public double getLog10(int source, int target) {
        return Math.log10(get(source, target));
    }
}
